package com.application.Activity;

import it.unipr.ce.dsg.s2p.sip.Address;

import java.util.ArrayList;

import ReadWriteXML.CMember;
import ReadWriteXML.ReadXML;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.application.Controller.ActivityController;
import com.application.Controller.NetworkController;
import com.application.Controller.ReadWriteFileController;
import com.application.Custom.ListUserAdapter;
import com.application.Network.PingThread;
import com.application.Network.Protocol;
import com.application.PhanQuyen.Quyen;
import com.application.outdoor.InvoikeServices.CayThaoLuanInvoike;
import com.application.outdoor.InvoikeServices.CommonInvoike;


public class frmNhomChoActivity extends Activity {

	
	public static int ON_EXIT_APP=1111;
	public static String NAME_CODE = "NAME_CODE";
	public static String IP_CODE = "IP_CODE";
	public static boolean groupFull = false;
	public static boolean isFirstStart=true;
	public static Runnable raRefreshListView;
	public static Runnable raStartGroup;
	ListView lvDanhSachThanhVien;
	Button btnMoiThanhVien, btnBatDau;
	TextView txtGroupName,txtCountCurrent;
	String groupName = "";
	
	ArrayList<CMember> memberList;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.layout_nhom_cho);
		lvDanhSachThanhVien = (ListView) findViewById(R.id.lvDanhSachThanhVien);
		btnMoiThanhVien = (Button) findViewById(R.id.btnMoiThanhVien);
		btnBatDau = (Button) findViewById(R.id.btnBatDau);
		txtGroupName = (TextView) findViewById(R.id.txtGroupName);
		
		txtCountCurrent=(TextView)findViewById(R.id.txtThanhVienHienTai);
		
		fillListView();
		
		registerForContextMenu(lvDanhSachThanhVien);
		btnMoiThanhVien.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			//	Quyen moiThanhVien = NetworkController._peer.getAccount().getRuleById(1);				
				if (NetworkController.getIsThanhLapNhom()) {
					if(NetworkController.isInDoor()){
					Intent intent = new Intent(getBaseContext(), frmDanhSachOnline.class);
					intent.putExtra(frmTaoNhom.CODE_GROUP_NAME, groupName);
					startActivity(intent);
					}else {
						if(NetworkController.isOutDoor()){
							btnMoiThanhVien.setText("Mời thảo luận");
							AlertDialog.Builder builder=new AlertDialog.Builder(frmNhomChoActivity.this);
							builder.setTitle("Mời vào thảo luận");
							final EditText txtTenDangNhap=new EditText(frmNhomChoActivity.this);	
							builder.setView(txtTenDangNhap);
							builder.setPositiveButton("Mời", new DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									String nguoiNhan=txtTenDangNhap.getText().toString();
									String nguoiGui=CommonUtilities.nguoiDung.getTenDangNhap();
									
									new CayThaoLuanInvoike().moiVaoThaoLuan(nguoiGui, nguoiNhan, CommonUtilities.idCayHienTai, CommonUtilities.idNhomHienTai);
									
								}
							});
							builder.setNegativeButton("Hủy bỏ", null);
							builder.show();
						}
					}
				} else {
					Show(Protocol.NON_RULE_MESSAGE);
				}
			}
		});
		
		btnBatDau.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (NetworkController.getIsThanhLapNhom()) {
					//Gui tin nhan start
					//outdoor
					if (NetworkController.isOutDoor()) {
						try {
							for (CMember m : memberList) {
								new CommonInvoike().guiTinNhan(CommonUtilities.nguoiDung.getId() + "", m.get_ip(), "noidung",
										Protocol.START_GROUP);
							}
						} catch (Exception e) {
							Log.d("Phu", "Không gửi tin nhắn start đc!");
						}
					} else {
						for (CMember member : memberList) {
							NetworkController.sendStartGroup(new Address(member.get_ip()));
						}
					}
				} else {
					Show(Protocol.NON_RULE_MESSAGE);
				}
			}
		});
		//ghi nho lai cac quyen mac dinh cua he thong
		ArrayList<Quyen> arrDefaultRule=ReadWriteFileController.readRule(getBaseContext(), ReadWriteFileController.RULE_BASE_PATH);
		NetworkController.defaultRule=arrDefaultRule;
		
		// Lấy tên nhóm từ activity trước
		Intent i = getIntent();
		if (i != null) {
			if (i.getStringExtra(frmTaoNhom.CODE_GROUP_NAME) != null)
				groupName = i.getStringExtra(frmTaoNhom.CODE_GROUP_NAME);
			
		}
		txtGroupName.setText("Nhóm "+groupName);
		

		txtGroupName.setText("Nhóm "+NetworkController.getGroupName());
		Log.d("Phu", "GroupName: " + txtGroupName.getText());
		
		raRefreshListView = new Runnable() {
			@Override
			public void run() {
				Log.d("Phu", "frmNhomChoActivity raRefreshListView");
				fillListView();
			}
		};
		raStartGroup=new Runnable() {
			
			@Override
			public void run() {
				startGroup();
			}
		};
		try{
		NetworkController._peer.getAccount().inGroup=true;
		}catch(Exception e){
			
		}
		
		// outdoor
//		if(NetworkController.isOutDoor()){
//			btnMoiThanhVien.setVisibility(View.GONE);			
//		}
	}

	private void fillListView() {
		int cur,tot;
		tot=NetworkController._peer.amountMemberGroup;//total
//		Log.v("Phu","Total in fill="+tot);
		cur=NetworkController.amountMember.size();//current
//		Log.v("Phu","current in fill="+cur);
		String s="Nhóm có "+cur+"/"+tot+" thành viên.";
		txtCountCurrent.setText(s);
		
//		Log.d("Phu","Refresh button");
		memberList = ReadXML.ReadMember(ReadWriteFileController.MEMBER_PATH);
//		Log.e("Phu","count memberList="+memberList.size());
//		ArrayAdapter<CMember> adapter = new ArrayAdapter<CMember>(this, android.R.layout.simple_list_item_1, memberList);
		ListUserAdapter adapter = new ListUserAdapter(this, R.layout.list_rolelist, memberList);
		lvDanhSachThanhVien.setAdapter(adapter);
//		Log.e("Phu","fill listview finish");
		
		if(NetworkController.isOutDoor()){
			
			cur=memberList.size();
			groupName=CommonUtilities.contacts.getGroupByID(CommonUtilities.idNhomHienTai).getTenNhom();
			tot=CommonUtilities.contacts.getSoLuongNguoiTrongNhom(CommonUtilities.idNhomHienTai);
			String s1="Nhóm có "+cur+"/"+tot+" thành viên.";
			
			txtGroupName.setText("Nhóm "+groupName+"");
			txtCountCurrent.setText(s1);
		}
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		if (v.getId() == R.id.lvDanhSachThanhVien) {
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
			if (NetworkController._peer.getAccount().get_Username()
					.equals(memberList.get(info.position).get_userName())) {
					Toast.makeText(getApplicationContext(), "Bạn không thể thao tác với chính mình.", Toast.LENGTH_LONG).show();
			} else {
				menu.setHeaderTitle("Thao tác");
				
				menu.addSubMenu(Menu.NONE, 1, 1, "Đặt vai trò").setIcon(R.drawable.quan_ly_role);
				// menu.addSubMenu(Menu.NONE, 2, 2, "Yêu cầu thoát");
				// menu.addSubMenu(Menu.NONE, 3, 3, "Chat");
			}
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
		int menuItemIndex = item.getItemId();
		if (menuItemIndex == 1) {
		//	Quyen setRoleChoNguoiKhac = NetworkController._peer.getAccount().getRule(Protocol.R_SET_VAI_TRO);
			if (NetworkController.getIsThanhLapNhom()){// || (setRoleChoNguoiKhac != null && setRoleChoNguoiKhac.getSend())) {
				Intent intent = new Intent(this, frmSetRoleActivity.class);
				intent.putExtra(NAME_CODE, memberList.get(info.position).get_fullName());
				intent.putExtra(IP_CODE, memberList.get(info.position).get_ip());
				intent.putExtra(Protocol.NGUOI_DUNG, memberList.get(info.position).get_userName());
				startActivity(intent);
			} else {
				Show(Protocol.NON_RULE_MESSAGE);
			}
		}
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		new MenuInflater(getApplication()).inflate(R.menu.omnu_nhom_cho, menu);
		return (super.onCreateOptionsMenu(menu));
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {
		case R.id.mnuMyRole:
			Intent intent = new Intent(getBaseContext(), frmVaiTroCuaToiActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}
		return true;
	}

	private void readGroupMember() {
		memberList = ReadXML.ReadMember(ReadWriteFileController.MEMBER_PATH);
	}

	 public static void insertMember(CMember member) {
		ReadWriteFileController.insertMember(ReadWriteFileController.MEMBER_PATH, member);
		Log.d("Phu", "insertMember trong frmNhomChoActivity");
	}

	public void Show(String message) {
		// Toast.makeText(this, "hehe Xin chao", Toast.LENGTH_SHORT).show();
		AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Thông báo").setMessage(message)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
					}
				}).create();
		dlg.show();
	}
	public  void startGroup(){
		
		if (!NetworkController.isOutDoor()) {
			Intent intent = new Intent(getBaseContext(), frmTreeNodeActivity.class);
			startActivity(intent);
			NetworkController.setStated(true);
			PingThread pingThread = new PingThread("Ping Nhom Cho");
			pingThread.start();
		} else {//outdoor
			od_SubjectActivity.getCay(CommonUtilities.idCayHienTai, frmNhomChoActivity.this);
			Intent intent = new Intent(getBaseContext(), frmTreeNodeActivity.class);
			startActivity(intent);
		}
		finish();
	}
	@Override
	public void onResume() {
		Log.d("Phu","onResume frmNhomChoActivity");
		super.onResume();
		fillListView();
	}
	@Override
	public void onStart(){
		Log.d("Phu","onStart frmNhomChoActivity");
		super.onStart();
		ActivityController.setPeerActivity(this);
		ActivityController.addActivityToArray(this);
		if(NetworkController._peer!=null&&(!NetworkController.getIsThanhLapNhom())){
//			ReadWriteFileController.deleteFile(ReadWriteFileController.MY_ROLE_PATH);
//			NetworkController.resetRole();
		}
		//Xóa file Tree
		ReadWriteFileController.deleteFile(ReadWriteFileController.TREE_PATH);
	}
	@Override
	public void onPause(){
		super.onPause();
		ActivityController.setPeerActivity(this);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.e("Phu","on onActivityResult nhom cho");
		 if (resultCode == ON_EXIT_APP) {
			// Intent i=new Intent(this, frmTreeNodeActivity.class);
			// Intent i=new Intent();
		//	 startActivityForResult(i, ON_EXIT_APP);
			 setResult(FrmTabActivity.ON_EXIT_APP);
			 finish();
		 }
	}
	public void Thoat() {
		ArrayList<CMember> cmem = ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
		for (int i = 0; i < cmem.size(); i++) {
			String name = String.valueOf(NetworkController._peer.getAccount().get_Username());
			Log.d("PEERDROID", "fullname: " + name);
			NetworkController.sendGroupSignOut(cmem.get(i).get_ip(), name);
		}
		NetworkController._peer.getAccount().setInGroup(false);
		// ghi xuống file Log
		String text = "Đã rời khỏi nhóm..";
		ReadWriteFileController.checkRuleWriteToLogFile(text);
		NetworkController._peer.amountMemberGroup=0;
		//NetworkController._peer.getAccount().isThanhLapNhom=false;
		finish();
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.d("PEERDROID", " vao on key down");
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setIcon(R.drawable.img_dialog);
			builder.setMessage("Bạn có chắc muốn rời khỏi nhóm hiện tại ?").setCancelable(false)
					.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int id) {
							if(NetworkController._peer.getAccount().isThanhLapNhom){
								NetworkController._peer.getAccount().isThanhLapNhom=false;
								NetworkController.amountMember.clear();
							}
							Thoat();
							
						}
					}).setNegativeButton("No", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
			AlertDialog alert = builder.create();
			alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0, 255, 255, 255)));
			alert.show();
			
		}
		return super.onKeyDown(keyCode, event);
	}
	
}
